// pages/payment/payment.js
import app from '../../index';
import api from '../../utils/request';
import util from '../../utils/util'

Page({

  /**
   * 页面的初始数据
   */
  data: {
    consumptionMoney: '', //金额

  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {

  },


  /* 输入付款金额 */
  changePaymentAmount(e) {
    let amount = util.amountControl(e.detail.inputAmount);
    this.setData({
      consumptionMoney: amount
    });
  },

  /**
   * 点击付款按钮
   */
  payment() {
    if (!this.data.consumptionMoney) {
      wx.showToast({
        title: '请输入付款金额！',
        icon: 'none',
        duration: 3000
      })
      return
    }
    this.beginPayment();

  },

  /**
   * 开始支付
   */
  beginPayment() {
    var that = this;
    var data = {
      orderUserOutPay: this.data.consumptionMoney, //户
      paymentList: [{
        paymentType: 'WX',
        amount: this.data.consumptionMoney,
        reduceValue: this.data.consumptionMoney
      }],
      orderType: 'FAST_PAY', //订单类型
      merchantId: 'T35202209070000001', //商户id
      orderTotalAmt: this.data.consumptionMoney, //订单总额 
    }

    api.post('CL020103', {
      data: data,
      showLoading: true,
      fail: true,
    }).then(datas => {
      if (datas.warningMessage != undefined && datas.warningMessage != '' && datas.warningMessage != null) {
        wx.showModal({
          content: datas.warningMessage,
          showCancel: false,
          success() {
            that.wxPay(datas);
          }
        })
      } else {
        that.wxPay(datas);
      }
    }).catch(res => {
      wx.showToast({
        title: res.message,
        icon: 'none',
        duration: 3000,
        mask: true
      });
    })
  },
  /**
   * 拉起微信支付
   */
  wxPay(datas) {
    var timeStamp = String(datas.wxInvokeInfo.timeStamp);
    var nonceStr = String(datas.wxInvokeInfo.nonceStr);
    var packageBny = String(datas.wxInvokeInfo.packageBny);
    var paySign = String(datas.wxInvokeInfo.paySign);
    var signType = String(datas.wxInvokeInfo.signType);

    wx.requestPluginPayment({
      fee: this.data.consumptionMoney,
      paymentArgs: {
        nonceStr: nonceStr,
        package: packageBny,
        paySign: paySign,
        signType: signType,
        timeStamp: timeStamp,
      },
      currencyType: 'USD',
      version: app.version,
      success(res) {
        wx.showModal({
          title: '支付成功',
          content: JSON.stringify(res),
          success: () => {}
        })

      },
      fail(err) {
        wx.showModal({
          title: '支付失败',
          content: JSON.stringify(err),
          success: () => {}
        })
      }
    })

  },

})